package com.kfm.servlet;

import com.kfm.model.FileDO;
import com.kfm.service.FileService;
import com.kfm.util.Contains;
import com.kfm.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    private FileService service = new FileService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 判断是否登录
        if (! LoginUtil.isLogin(getServletContext())){
            response.sendRedirect("login");
            return;
        }

        // localhost:80/upload/download?id=3
        String idStr = request.getParameter("id");

        if (idStr != null){
            int id = Integer.parseInt(idStr);
            FileDO fileDO = service.queryById(id);

            if (fileDO != null){
                String path = fileDO.getPath();
                response.setHeader("Content-Disposition", "inline; filename=" + fileDO.getName());

                try (FileInputStream fis = new FileInputStream(new File(Contains.FILE_PATH, path))){
                    fis.transferTo(response.getOutputStream());
                } catch (Exception e){
                    System.out.println("获取文件失败");
                }
            }
        }

    }
}
